
#include <wsnos.h>

/************************************************************/

static list_head_t osel_event_list_head[OSEL_MAX_PRIO];   	
task_cb g_task_cb[OSEL_MAX_PRIO];

static osel_task_handler osel_idle_task_handler;

#ifdef OSEL_DEBUG
static osel_uint8_t osel_register_grp = 0;
static osel_uint8_t osel_register_tbl[(OSEL_MAX_PRIO/8) + 1];
#endif
/************************************************************/
void osel_init(void) 
{
	osel_mem_init();
	osel_sub_init();									
	osel_epool_init(OSEL_EPOOL_NUM);					
	osel_eblock_init(OSEL_EBLOCK_NUM);				
	osel_rdy_grp = 0x00;							
	osel_memset(&osel_rdy_tbl[0], 0x00, OSEL_DIM(osel_rdy_tbl));
}

task_cb *osel_task_create(osel_task_handler handler, 
                     		osel_uint8_t prio)
{		
	osel_uint8_t i = 0;
	OSEL_ASSERT(prio < OSEL_MAX_PRIO);

	OSEL_INT_LOCK();
#ifdef OSEL_DEBUG
	if((osel_register_grp & osel_map_tbl[prio >> 3]) == osel_map_tbl[prio >> 3]
		&& ((osel_register_tbl[prio >> 3] & osel_map_tbl[prio & 0x07]) 
			== osel_map_tbl[prio & 0x07]))
	{
		OSEL_ASSERT(OSEL_FALSE);
	}
	osel_register_grp |= osel_map_tbl[prio >> 3];
    osel_register_tbl[prio >> 3] |= osel_map_tbl[prio & 0x07];
	
	for(i=0; i<OSEL_MAX_PRIO; i++)
	{
		if(g_task_cb[i].task.handler == handler)
		{
			OSEL_ASSERT(OSEL_FALSE);
		}
	}
#endif
    task_cb *tcb  = &g_task_cb[prio];
	tcb->task.handler = handler;
	tcb->task.prio = prio;
	tcb->queue = osel_event_list_head[prio];
	list_init(&tcb->queue);
	
	OSEL_INT_UNLOCK();
	return tcb;
}

void osel_idle_sethook(osel_task_handler idle)
{
	if(idle != OSEL_NULL)
	{
		osel_idle_task_handler = idle;
	}
}

void osel_onidle(void) 
{
    if(osel_idle_task_handler != OSEL_NULL)
    {
		osel_idle_task_handler(OSEL_NULL);
	}
}

void osel_run(void) 
{
    osel_start();                                            

    OSEL_INT_LOCK();
    osel_schedule();                     	
    OSEL_INT_UNLOCK();

    while(1) 
    {                              			
        osel_onidle();                       
    }
}

/**@}**/

